import router from './router'
import store from './store'
import NProgress from 'nprogress' // 做涓流动画的插件
import 'nprogress/nprogress.css' //  做涓流动画的插件样式

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // 定义白名单

router.beforeEach(async (to, from, next) => {
  NProgress.start() // 开启进度条
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        // 判断是否有用户资料
        const { roles } = await store.dispatch('user/getUserInfo') // 获取用户资料
        const routes = await store.dispatch('permission/filterRoutes', roles.menus) // 筛选路由 筛选当前用户所拥有的动态路由
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }]) // 添加动态路由到路由表，404页面应该添加到最后
        next(to.path) //  注意添加了动态路由写法  跳到对应地址 相当于多做一次跳转  不能用next()
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done() // 关闭进度条   解决手动切换地址进度条不关闭问题
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
